package TamirsGui;

import java.util.Vector;

import TamirsGui.GuiMessage.MessageAuthorization;
import TamirsGui.GuiMessage.MessageSubType;
import TamirsGui.GuiMessage.MessageType;

public class MainWindowMsg{

	public MainWindowMsg(){
		
	}
	public MainWindowMsg(String messageFromServer) {
		this.parseMessage(messageFromServer);
	}
	/**
	 * 
	 * @param messageFromServer the received messaged from the server. we know that the message is for the main gui window.
	 * here we parse the message for the format of the dispatch thread.
	 * @return vector of messages for the main window which the dispatch thread knows how to handle. 
	 */
	public Vector<GuiMessage> parseMessage(String messageFromServer) {
		String[] splitedMessage;
		int messagePopupLength = "popupMessage".length();
		if(messageFromServer.length() >messagePopupLength && messageFromServer.substring(0, messagePopupLength-1).equalsIgnoreCase("popupMessage")){
			StringBuilder sb = new StringBuilder(messageFromServer);
			String messageTopic = getMessageNextPiceOfInfor(sb, (char)1+"");
			splitedMessage = new String[3];
			for(int i = 0 ; i <3;i++){
				splitedMessage[i] = getMessageNextPiceOfInfor(sb, (char)1+"");
				return this.getMessageInfo(messageTopic , splitedMessage);
			}
			
		}
		if(messageFromServer.substring(0, 8).equalsIgnoreCase("postList")){
			splitedMessage = messageFromServer.split((char)1+"");
		}
		else
			splitedMessage = messageFromServer.split((char)1+"");
		int messageLength = splitedMessage.length;
		String [] messageWithoutTopic = new String[messageLength -1];
		System.arraycopy(splitedMessage, 1, messageWithoutTopic, 0, messageLength -1);
		String messageTopic = splitedMessage[0]; 
		return this.getMessageInfo(messageTopic , messageWithoutTopic);
	}

	private Vector<GuiMessage> getMessageInfo(String messageTopic,
			String[] messageWithoutTopic) {
		Vector<GuiMessage> serverMessages = new  Vector<GuiMessage>();
		if(messageTopic.equalsIgnoreCase("login")){
			buildLoginMsg(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("register")){
			buildRegisterMsg(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("ThreadsList")){
			buildThreadListMsg(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("postList")){
			buildPostListMsg(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("addedSubForum")){
			buildaddedSubForumMsg(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("CandidatesList")){
			buildCandidateListMsg(serverMessages,messageWithoutTopic,messageTopic,"admin");
		}
		if(messageTopic.equalsIgnoreCase("ModeratorAdd")){
			buildModeratorAdd(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("MsgDeleted")){
			buildMsgDeletedAck(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("SubForumDeleted")){
			BuildSubForumDeletedAck(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("MsgEdited")){
			buildMsgEditedAck(serverMessages,messageWithoutTopic,messageTopic);
		}

		if(messageTopic.equalsIgnoreCase("ModeratorRemoved")){
			buildModeratorRemovedAck(serverMessages,messageWithoutTopic,messageTopic);
		}
		if(messageTopic.equalsIgnoreCase("ModeratorList")){
			buildModeratorList(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("SubForumList")){
			buildSubForumList(serverMessages,messageWithoutTopic,messageTopic);
		}
        if (messageTopic.equalsIgnoreCase("AddThread") || messageTopic.equalsIgnoreCase("addPostMessage")) {
			buildAddMessageAck(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("popupMessage")){
			buildPopupMessage(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("pathNotFound")){
			buildPathNotFoundAck(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("numOfMsgs")){
			buildGetNumOfMsgs(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("msgsByUser")){
			buildUsersList(serverMessages,messageWithoutTopic,messageTopic);
		}
        if(messageTopic.equalsIgnoreCase("msgsCount")){
			buildUserMsgCount(serverMessages,messageWithoutTopic,messageTopic);
		}
        if (messageTopic.equalsIgnoreCase("adminCandidate")){
            buildAdminCandidateList(serverMessages,messageWithoutTopic,messageTopic);
        }
        if (messageTopic.equalsIgnoreCase("changeAdmin")){
            buildChangeAdminAck(serverMessages,messageWithoutTopic,messageTopic);
        }
        if (messageTopic.equalsIgnoreCase("numOfConnection")){
            buildNumOfConnectionAck(serverMessages,messageWithoutTopic,messageTopic);
        }
        if (messageTopic.equalsIgnoreCase("doRefresh"))
        {
            buildDoRefresh(serverMessages,messageWithoutTopic,messageTopic);
        }
        
        
		return serverMessages;


	}
	private void buildUserMsgCount(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic, messageTopic,MessageSubType.numOfMessages);
		
	}
	private void buildUsersList(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
			String authorization = "guest";
		for(int i = 1 ; i < messageWithoutTopic.length; i++){
			String body = messageTopic;
			String title = messageWithoutTopic[i];
			if(title.equals("\n"))
				continue;
			MessageType type = MessageType.content;
			MessageSubType subType = MessageSubType.usersList;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
			serverMessages.add(newGuiMessage);
		}
		
		
	}
	private void buildGetNumOfMsgs(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic, MessageSubType.numOfMessages);	
	}
	
	private String getMessageNextPiceOfInfor(StringBuilder message ,String delemiter){
		int nextIndexToSplit = message.indexOf(delemiter);
		String nextPice = message.toString();
		if (nextIndexToSplit > 0){
			nextPice = message.substring(0,nextIndexToSplit -1);
			String restOfMessage =message.substring(nextIndexToSplit+1);
			message = new StringBuilder(restOfMessage);
			}
		return nextPice;
	}
	
	private void buildPopupMessage(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
			String authorization ="guest";
			String userName = messageWithoutTopic[0];
			String title = messageWithoutTopic[1];
			String body = messageWithoutTopic[2];
			MessageType type = MessageType.popup;
			MessageSubType subType = MessageSubType.postMsg;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
			serverMessages.add(newGuiMessage);
	}
	
	private void buildModeratorList(Vector<GuiMessage> serverMessages,
		String[] messageWithoutTopic, String messageTopic) {
		String authorization = messageWithoutTopic[0]; 
		for(int i = 1 ; i < messageWithoutTopic.length; i++){
			String body = messageTopic;
			String title = messageWithoutTopic[i];
			if(title.equals("\n"))
				continue;
			MessageType type = MessageType.content;
			MessageSubType subType = MessageSubType.moderatorList;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
			serverMessages.add(newGuiMessage);
		}
	}

	private void buildModeratorRemovedAck(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic, MessageSubType.moderatorRemoved);			
	}

	private void buildAllAckMesages(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic,String messageTopic,MessageSubType subType) {
		String authorization = "guest";
		String title = messageTopic;
		String body = "";
		for(int i = 0 ; i < messageWithoutTopic.length-1;i++)
			body+=messageWithoutTopic[i]+"\n";
		MessageType type = MessageType.ack;
		MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
		GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
		serverMessages.add(newGuiMessage);		
	}

	private void buildMsgEditedAck(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.msgEdited);	
		
	}

	private void BuildSubForumDeletedAck(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.subForumDeleted);	
		
	}

	private void buildMsgDeletedAck(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.msgDeleted);	
		
	}

	private void buildModeratorAdd(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.moderatorAdded);	
		
	}

	private void buildCandidateListMsg(Vector<GuiMessage> serverMessages,
		String[] messageWithoutTopic, String candidateList,String autho) {
		String authorization = autho; 
		for(int i = 0 ; i < messageWithoutTopic.length -1; i++){
			String body = messageWithoutTopic[i];
			String title = messageWithoutTopic[i];
			MessageType type = MessageType.content;
			MessageSubType subType = MessageSubType.candidateList;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
			serverMessages.add(newGuiMessage);
		}
		
	}

	private void buildaddedSubForumMsg(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		if(messageWithoutTopic[1].equalsIgnoreCase("success")){
			String[] stubMessage = {messageWithoutTopic[2],"success"};
			buildAllAckMesages(serverMessages, stubMessage,messageTopic,MessageSubType.subForumAdded);
			serverMessages.elementAt(0).setMessageId(stubMessage[0]);
			int arraySize = messageWithoutTopic.length-4;
			String[] candidates = new String [arraySize];
			System.arraycopy(messageWithoutTopic, 4,candidates, 0, arraySize);
			String athorization = messageWithoutTopic[0];
			buildCandidateListMsg(serverMessages,candidates,"CandidateList",athorization);
			
		}
		else{
			String[] stubMessage = {messageWithoutTopic[1],"failed"};
			buildAllAckMesages(serverMessages, stubMessage,messageTopic,MessageSubType.subForumAdded);
			serverMessages.elementAt(0).setMessageId(stubMessage[0]);
		}
		
	}

	//@TODO to chage the delimiter from \n
	private void buildPostListMsg(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
			String authorization = messageWithoutTopic[0]; 
			String[] posts = new String [messageWithoutTopic.length -1];
			System.arraycopy(messageWithoutTopic, 1, posts,0, messageWithoutTopic.length -1);
			System.out.println(posts.length);
			if(posts.length == 1)
				buildEmptyPostList(serverMessages,authorization);
//			String[] msgTitleAndBody = posts.split("/n");
			for(int i = 0 ; i < posts.length - 1; i++){
				System.out.println(posts[i]);
				String postMsg = posts[i];
				String[] msg = postMsg.split((char)2+"");
				String messageHeader = msg[0];
				String[] messageInfo = messageHeader.split(":");
				String messageId = messageInfo[0];
				String title = (messageInfo.length >1 ? messageInfo[1] : "noSubject");
				authorization = msg[1];
				String body = (msg.length >2  ? msg[2] : " ");;		
				System.out.println(title+" "+body+" "+authorization);
				MessageType type = MessageType.content;
				MessageSubType subType = MessageSubType.postMsg;
				MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
				GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization,messageId);
				serverMessages.add(newGuiMessage);
			}
	}

	private void buildEmptyPostList(Vector<GuiMessage> serverMessages, String authorization) {
		String body = "";
		String title = "";
		MessageType type = MessageType.content;
		MessageSubType subType = MessageSubType.postMsg;
		MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
		GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
		serverMessages.add(newGuiMessage);

		
	}
	private void buildThreadListMsg(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
            System.out.println("i am buliding threads");
		String authorization = messageWithoutTopic[0]; 
                                            int numberOfMessages =  messageWithoutTopic.length -1;
                                            if(numberOfMessages == 1)
                                                buildEmptyThreadMsg(serverMessages,authorization);
		for(int i = 1 ; i < numberOfMessages; i++){
			String body = "";
			String messageHeader = messageWithoutTopic[i];
			String[] messageInfo = messageHeader.split(":");
			String messageId = messageInfo[0];
			String title = (messageInfo.length > 1 ? messageInfo[1] : "noTitle");
			MessageType type = MessageType.content;
			MessageSubType subType = MessageSubType.threadMsg;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization,messageId);
			serverMessages.add(newGuiMessage);
		}
		
	}

	private void buildRegisterMsg(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		String authorization = messageWithoutTopic[0];
		System.out.println(messageTopic);
		String title = messageTopic;
		String body = "";
		for(int i = 1 ; i < messageWithoutTopic.length-1;i++)
			body+=messageWithoutTopic[i]+"\n";
		MessageType type = MessageType.ack;
		MessageSubType subType = MessageSubType.registerAck;
		MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
		GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
		serverMessages.add(newGuiMessage);		
				
	}

	private void buildLoginMsg(Vector<GuiMessage> serverMessages,
			String[] messageWithoutTopic, String messageTopic) {
		String authorization = messageWithoutTopic[0];
		String title = messageTopic;
		String body = "";
		for(int i = 1 ; i < messageWithoutTopic.length-1;i++)
			body+=messageWithoutTopic[i]+"\n";
		MessageType type = MessageType.ack;
		MessageSubType subType = MessageSubType.loginAck;
		MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
		GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
		serverMessages.add(newGuiMessage);		
		
	}

    private void buildSubForumList(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
                                           String authorization = messageWithoutTopic[0];
		String title;
                                           String subForumName ;
                                           String messageId;
                                           String body = "";
		for(int i = 1 ; i < messageWithoutTopic.length-1;i++){
                                                    subForumName = messageWithoutTopic[i];
                                                    String[] forumTitles =  subForumName .split(":");
                                                    title = forumTitles[1];
                                                    messageId = forumTitles[0];
                                                    MessageType type = MessageType.content;
                                                    MessageSubType subType = MessageSubType.subForum;
                                                    MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
//                                                    GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
                                                      GuiMessage newGuiMessage =new GuiMessage(body, title, type, subType, userAutoAuthorization, messageId);
                                                    serverMessages.add(newGuiMessage);		
		
    }



}

    private void buildEmptyThreadMsg(Vector<GuiMessage> serverMessages, String authorization) {
                            MessageType type = MessageType.content;
                            MessageSubType subType = MessageSubType.threadMsg;
                             MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
                            String  body = "";
                            String  title = "";
                            String messageId = "";
                           GuiMessage newGuiMessage =new GuiMessage(body, title, type, subType, userAutoAuthorization, messageId);
                           serverMessages.add(newGuiMessage);;
        
    }

    private void buildAddMessageAck(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
        		buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.addedMsgAck);	

    }

    private void buildPathNotFoundAck(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
        buildAllAckMesages(serverMessages, messageWithoutTopic,messageTopic,MessageSubType.pathNotFound);	
    }

    private void buildAdminCandidateList(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
        String authorization = messageWithoutTopic[0]; 
		for(int i = 1 ; i < messageWithoutTopic.length; i++){
			String body = messageTopic;
			String title = messageWithoutTopic[i];
			if(title.equals("\n"))
				continue;
			MessageType type = MessageType.content;
			MessageSubType subType = MessageSubType.adminList;
			MessageAuthorization userAutoAuthorization = MessageAuthorization.valueOf(authorization);
			GuiMessage newGuiMessage = new GuiMessage(body, title, type, subType, userAutoAuthorization);
			serverMessages.add(newGuiMessage);
		}
    }

    private void buildChangeAdminAck(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
            buildAllAckMesages(serverMessages, messageWithoutTopic, messageTopic, MessageSubType.changeAdminAck);
    }

    private void buildNumOfConnectionAck(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
        buildAllAckMesages(serverMessages, messageWithoutTopic, messageTopic, MessageSubType.numOfConnectionAck);
    }

    private void buildDoRefresh(Vector<GuiMessage> serverMessages, String[] messageWithoutTopic, String messageTopic) {
        serverMessages.add(new GuiMessage("", messageTopic, MessageType.refresh, null, MessageAuthorization.guest));
    }
}